import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/CentrePage/Device/DeviceStop02.dart';
import 'package:flutter_wisave/CentrePage/Device/DeviceData02.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '../Equipment/BreakItem.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../Device/BreakdownDetailPage.dart';
import '../../Tools/ToolsLocalStorage.dart';
import '../../widgets/AppColors.dart';

class EquipmentPage extends StatefulWidget {
  final int initialIndex;

  const EquipmentPage({
    super.key,
    this.initialIndex = 0,
  });

  @override
  State<EquipmentPage> createState() => _EquipmentPageState();
}

class _EquipmentPageState extends State<EquipmentPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  bool breakdown = false;
  final NetworkService _networkService = NetworkService();
  List<dynamic> malfunctions = [];
  List<dynamic> userMalfunctions = [];

  List<String> nameList = ['  实时监控1', '  实时监控2'];
  var childName = '  实时监控1';

  //生命周期函数：当组件初始化的时候就会触发
  //输入inits可快速生成该方法
  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 3,
      vsync: this,
      initialIndex: widget.initialIndex,
    );
    _loadData();
  }

  Future<void> _loadRefresh() async {
    TDToast.showSuccess('操作成功',
        direction: IconTextDirection.vertical, context: context);
    _loadData();
  }

  //设备故障
  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result != null && result['rows'] != null) {
        setState(() {
          malfunctions = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }

    try {
      final result = await _fetchUserData();
      if (result != null && result['rows'] != null) {
        setState(() {
          userMalfunctions = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService
          .get('/plcTimer/malfunctiontype/selecList?companyId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchData: $e');
      rethrow;
    }
  }

  Future<Map<String, dynamic>> _fetchUserData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService
          .get('/plcTimer/malfunctiontype/selecListByUserId?companyId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchData: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏颜色
    ));
    // 获取屏幕的宽度和高度
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;
    final screenHeight = mediaQuery.size.height;

    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        title: const Text('设备管理'),
        foregroundColor: AppColors.textPrimary,
        centerTitle: true,
        backgroundColor: Colors.transparent, // Make AppBar transparent
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(48), // Adjust height as needed
          child: Container(
            decoration: const BoxDecoration(
              color: Colors.transparent, // Set the background color
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
            ),
            child: TabBar(
              isScrollable: false,
              indicatorColor: Colors.blue,
              indicatorWeight: 2,
              indicatorPadding: const EdgeInsets.only(right: 50, left: 50),
              indicatorSize: TabBarIndicatorSize.tab,
              labelColor: TDTheme.of(context).grayColor12,
              unselectedLabelColor: TDTheme.of(context).grayColor8,
              labelStyle:
                  const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              unselectedLabelStyle: const TextStyle(fontSize: 16),
              controller: _tabController,
              tabs: [
                Tab(
                    child: Text("故障报警",
                        style: TextStyle(color: AppColors.textPrimary))),
                Tab(
                    child: Text("实时监控",
                        style: TextStyle(color: AppColors.textPrimary))),
                Tab(
                    child: Text("设备诊断",
                        style: TextStyle(color: AppColors.textPrimary))),
              ],
            ),
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          ListView(
            children: [
              const SizedBox(height: 20),
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ..._buttonWithType(
                          '我的关注', screenWidth, !this.breakdown, 0, () {
                        setState(() {
                          this.breakdown = false;
                        });
                      }),
                      const SizedBox(width: 10), // Add spacing between buttons
                      ..._buttonWithType('全部故障', screenWidth, this.breakdown, 0,
                          () {
                        setState(() {
                          this.breakdown = true;
                        });
                      }),
                    ],
                  ),
                  const SizedBox(height: 20),
                  Container(
                    height: MediaQuery.of(context).size.height - 220, // 调整高度
                    child: GridView.builder(
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        childAspectRatio: MediaQuery.of(context).size.width /
                            (2 * 100), // 调整这个值以适应您想要的高度
                        mainAxisSpacing: 1, // 添加垂直间距
                        crossAxisSpacing: 10, // 添加水平间距
                      ),
                      itemCount: !breakdown
                          ? userMalfunctions.length
                          : malfunctions.length,
                      itemBuilder: (context, index) {
                        return GestureDetector(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      const BreakdownDetailPage()),
                            );
                            print(
                                'Item clicked: ${!breakdown ? userMalfunctions[index] : malfunctions[index]}');
                          },
                          child: BreakItem(
                            data: !breakdown
                                ? userMalfunctions[index]
                                : malfunctions[index],
                            onRefresh: _loadRefresh,
                          ),
                        );
                      },
                    ),
                  )
                ],
              ),
            ],
          ),
          ListView(
            children: [
              Container(
                margin: const EdgeInsets.all(15),
                height: 50,
                decoration: BoxDecoration(
                  color: AppColors.cardColor,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: GestureDetector(
                  onTap: () {
                    TDPicker.showMultiPicker(context, title: '',
                        onConfirm: (selected) {
                      setState(() {
                        childName = '${nameList[selected[0]]}';
                      });
                      Navigator.of(context).pop();
                    }, data: [nameList]);
                  },
                  child: Row(
                    children: [
                      Text(childName,
                          style: TextStyle(color: AppColors.textPrimary)),
                      Image.asset('assets/images/centre/icon_down.png'),
                    ],
                  ),
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Image.asset(
                    childName == '  实时监控1'
                        ? 'assets/images/centre/1.gif'
                        : 'assets/images/centre/2.gif',
                    width: screenWidth - 30,
                    fit: BoxFit.fitWidth,
                  ),
                ],
              ),
            ],
          ),
          ListView(
            children: [
              const SizedBox(height: 20),
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  //不要展示
                  // Row(
                  //   mainAxisSize: MainAxisSize.max,
                  //   mainAxisAlignment: MainAxisAlignment.center,
                  //   children: [
                  //     ..._buttonWithType(
                  //         '每周数据', screenWidth, !this.breakdown, 2, () {
                  //       setState(() {
                  //         this.breakdown = false;
                  //       });
                  //     }),
                  //     const SizedBox(width: 10), // Add spacing between buttons
                  //     ..._buttonWithType('每月数据', screenWidth, this.breakdown, 2,
                  //         () {
                  //       setState(() {
                  //         this.breakdown = true;
                  //       });
                  //     }),
                  //   ],
                  // ),
                  DeviceStop02(height: 330),
                  DeviceData02()
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }
}

List<Widget> _buttonWithType(String title, double screenWidth, bool select,
    int tabIndex, VoidCallback onTap) {
  String imgBg = AppColors.isDarkMode
      ? 'assets/images/cloud/cloud_gray_b.png'
      : 'assets/images/cloud/cloud_gray.png';
  String imgIcon = 'assets/images/cloud/icon_gray.png';
  if (tabIndex == 0) {
    if (select) {
      if (title == '我的关注') {
        imgBg = AppColors.isDarkMode
            ? 'assets/images/cloud/cloud_blue_b.png'
            : 'assets/images/cloud/cloud_blue.png';
        imgIcon = 'assets/images/cloud/icon_blue.png';
      } else {
        imgBg = AppColors.isDarkMode
            ? 'assets/images/cloud/cloud_orange_b.png'
            : 'assets/images/cloud/cloud_orange.png';
        imgIcon = 'assets/images/cloud/icon_orange.png';
      }
    } else {
      imgBg = AppColors.isDarkMode
          ? 'assets/images/cloud/cloud_gray_b.png'
          : 'assets/images/cloud/cloud_gray.png';
      if (title == '我的关注') {
        imgIcon = 'assets/images/cloud/icon_blue_un.png';
      } else {
        imgIcon = 'assets/images/cloud/icon_gray.png';
      }
    }
  } else if (tabIndex == 2) {
    if (select) {
      imgBg = AppColors.isDarkMode
          ? 'assets/images/cloud/cloud_blue_b.png'
          : 'assets/images/cloud/cloud_blue.png';
      if (title == '每周数据') {
        imgIcon = 'assets/images/cloud/icon_week.png';
      } else {
        imgIcon = 'assets/images/cloud/icon_month.png';
      }
    } else {
      imgBg = AppColors.isDarkMode
          ? 'assets/images/cloud/cloud_gray_b.png'
          : 'assets/images/cloud/cloud_gray.png';
      if (title == '每周数据') {
        imgIcon = 'assets/images/cloud/icon_week_un.png';
      } else {
        imgIcon = 'assets/images/cloud/icon_month_un.png';
      }
    }
  }

  return [
    GestureDetector(
      onTap: onTap,
      child: Container(
        height: 50,
        width: (screenWidth - 50) / 2,
        decoration: BoxDecoration(
          // color: Colors.white, // Add white background
          image: DecorationImage(
            image: AssetImage(imgBg),
            fit: BoxFit.cover,
          ),
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Stack(
          children: [
            Positioned.fill(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const SizedBox(
                      width: 8), // Add some space between image and text
                  Image.asset(
                    imgIcon, // Replace with your image path
                    width: 30, // Adjust size as needed
                    height: 30,
                  ),
                  const SizedBox(
                      width: 12), // Add some space between image and text
                  Text(
                    title,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: AppColors.textPrimary,
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    ),
  ];
}
